//MountManager - the program for easy mounting of storage devices in Linux
//Copyright (C) 2007-2008 Tikhonov Sergey
//
//This file is part of MountManager Plugin "Shares mounting"
//
//This program is free software; you can redistribute it and/or
//modify it under the terms of the GNU General Public License
//as published by the Free Software Foundation; either version 2
//of the License, or (at your option) any later version.
//
//This program is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//GNU General Public License for more details.
//
//You should have received a copy of the GNU General Public License
//along with this program; if not, write to the Free Software
//Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
#include <QtGui/QAction>
#include <QtGui/QPushButton>
#include <QtGui/QHBoxLayout>
#include <QtGui/QVBoxLayout>
#include <QtCore/QSettings>
#include <QtCore/QFile>
#include <QtCore/QTextStream>
#include <QtPlugin>
#include <QDebug>
#include "sharesview.h"
#include "dialog.h"
#include "../../sources/gui/const.h"
#include "shareswizard.h"
#include "sharesmount.h"

SharesMount::SharesMount(QWidget *parent) {
	sharesWizard = new SharesWizard(parent);
	connect(sharesWizard,SIGNAL(finished()),this,SLOT(add()));
	
	mainWidget = new Dialog(parent);
	mainWidget->setWindowTitle(tr("Shares mounting"));
	mainWidget->setWindowIcon(QIcon(":/icons/share_mount.png"));
	connect(mainWidget,SIGNAL(shown()),this,SLOT(searchSharesLinesInFstab()));

	treeWidget = new SharesView;
	treeWidget->setHeaderLabels(QStringList() << tr("Type") << tr("Server") << tr("Server Path"));
	connect(treeWidget,SIGNAL(currentItemChanged(QTreeWidgetItem*,QTreeWidgetItem*)),this,SLOT(itemChanged(QTreeWidgetItem *,QTreeWidgetItem *)));

	addButton = new QPushButton(tr("Add"));
	connect(addButton,SIGNAL(clicked()),sharesWizard,SLOT(exec()));
	
	removeButton = new QPushButton(tr("Remove"));
	removeButton->setEnabled(false);
	connect(removeButton,SIGNAL(clicked()),this,SLOT(remove()));

	QAction *mainAction = new QAction(mainWidget);
	mainAction->setText(tr("Shares mounting"));
	mainAction->setIcon(QIcon(":/icons/share_mount.png"));
	actions.append(mainAction);
	connect(mainAction,SIGNAL(triggered()),mainWidget,SLOT(show()));

	QHBoxLayout *buttonsLayout = new QHBoxLayout;
	buttonsLayout->addWidget(addButton);
	buttonsLayout->addWidget(removeButton);
	buttonsLayout->addStretch();
	
	QVBoxLayout *mainLayout = new QVBoxLayout;
	mainLayout->addWidget(treeWidget);
	mainLayout->addLayout(buttonsLayout);
	mainWidget->setLayout(mainLayout);

	loadSettings();
	searchSharesLinesInFstab();
}

SharesMount::~SharesMount() {
	delete sharesWizard;
	foreach (QAction *action,actions)
		delete action;
	delete treeWidget;
	delete addButton;
	delete removeButton;
	delete mainWidget;
}

void SharesMount::setParent(QObject *parent) {
	connect(parent,SIGNAL(finished()),this,SLOT(saveSettings()));
}

const QString SharesMount::pluginName() const {
	return tr("Shares mounting");
}

const QString SharesMount::pluginDescription() const {
	return tr("With help of this plugin you can easy mount NFS and Samba shares or set them on auto-mount.");
}
	
QDialog* SharesMount::dialog() const {
	return mainWidget;
}

QDockWidget* SharesMount::dockWidget() const {
	return 0;
}

QMenu* SharesMount::menu() const {
	return 0;
}

QToolBar* SharesMount::toolBar() const {
	return 0;
}

Actions SharesMount::menuActions() const {
	return actions;
}
void SharesMount::saveSettings() {
	searchSharesLinesInFstab();
	QFile fstabFile("/etc/fstab");
	if (fstabFile.open(QIODevice::WriteOnly)) {
		QTextStream fstabStream(&fstabFile);
		fstabStream << fstabTextExceptShares;
		for (int i = 0; i < treeWidget->topLevelItemCount(); i++)
			if (treeWidget->topLevelItem(i) != 0) {
				QTreeWidgetItem *item = treeWidget->topLevelItem(i);
				if (item->text(0) == "NFS")
					fstabStream << item->text(1) << ':' << item->text(2) << '\t' << item->data(0,Qt::UserRole).toStringList()[0] << "\tnfs\t" << item->data(0,Qt::UserRole).toStringList()[1] << '\n';
				else {
					fstabStream << "//" << item->text(1);
					if (!item->text(2).startsWith('/'))
						fstabStream << '/';
					fstabStream << item->text(2) << '\t' << item->data(0,Qt::UserRole).toStringList()[0] << "\tsmbfs\t" << "username=" + item->data(0,Qt::UserRole).toStringList()[2] + ",password=" + item->data(0,Qt::UserRole).toStringList()[3] << "\t0\t0\n";
				}
			}
	} else
		qDebug() << tr("Cannot add Share records to fstab file");
	
	QSettings settings(ORGANIZATION,PROGRAM_NAME);
	settings.setValue("SharesMount/Size",mainWidget->size());
}

void SharesMount::loadSettings() {
	QSettings settings(ORGANIZATION,PROGRAM_NAME);
	mainWidget->resize(settings.value("SharesMount/Size",QSize(400,200)).toSize());
}

void SharesMount::add() {
	QTreeWidgetItem *newItem = new QTreeWidgetItem(treeWidget);
	newItem->setText(0,sharesWizard->getType());
	newItem->setText(1,sharesWizard->getServer());
	newItem->setText(2,sharesWizard->getServerPath());
	QString options = sharesWizard->getOptions().isEmpty() ? "defaults" : sharesWizard->getOptions();
	newItem->setData(0,Qt::UserRole,QStringList() << sharesWizard->getMountPoint() << options << sharesWizard->getName() << sharesWizard->getPassword());
}


void SharesMount::searchSharesLinesInFstab() {
	treeWidget->clear();
	QFile fstabFile("/etc/fstab");
	fstabFile.open(QIODevice::ReadOnly);
	QTextStream fstabStream(&fstabFile);
	fstabTextExceptShares.clear();
	while (!fstabStream.atEnd()) {
		QString line = fstabStream.readLine();
		if (line.contains("#"))
			continue;
		if (line.isEmpty())
			continue;
		line.replace("\t"," ");
		QStringList list = line.split(" ");
		list.removeAll("");
		list.removeAll(" ");
		if (list.count() == 4 && list[2] == "nfs") {
			QStringList serverWithRemoteDir = list[0].split(":");
			if (serverWithRemoteDir.count() != 2)
				continue;
			QTreeWidgetItem *item = new QTreeWidgetItem(treeWidget);
			item->setText(0,"NFS");
			item->setText(1,serverWithRemoteDir[0]);
			item->setText(2,serverWithRemoteDir[1]);
			item->setData(0,Qt::UserRole,QStringList() << list[1] << list[3] << "" << "");
		} else if (list.count() == 6 && list[2] == "smbfs") {
			if (list[0].startsWith("//")) {
				int endOfServer = list[0].indexOf('/',2);
				QString server = list[0].left(endOfServer).remove(0,2);
				QString remoteDir = list[0].remove("//" + server);
				QTreeWidgetItem *item = new QTreeWidgetItem(treeWidget);
				item->setText(0,"Samba");
				item->setText(1,server);
				item->setText(2,remoteDir);
				QString name = list[3].split(",")[0].remove("username=");
				QString password = list[3].split(",")[1].remove("password=");
				item->setData(0,Qt::UserRole,QStringList() << list[1] << "" << name << password);
			}
		} else
			fstabTextExceptShares += line + '\n';
	}
}

void SharesMount::itemChanged(QTreeWidgetItem *currentItem,QTreeWidgetItem *) {
	if (currentItem == 0)
		currentItem = treeWidget->currentItem();
	removeButton->setEnabled(currentItem != 0);
}

void SharesMount::remove() {
	QTreeWidgetItem *item = treeWidget->currentItem();
	if (item == 0)
		return;
	delete item;
	itemChanged(0,0);
}

Q_EXPORT_PLUGIN2(sharesmountplugin,SharesMount)
